package org.jdsm.flow.contact.impl.gae;

import org.jdsm.flow.contact.impl.IMailSender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * User: mikom
 * Date: 2/6/13
 * Time: 5:15 PM
 */
public class GAEIMailSender implements IMailSender {
    private static final Logger log = LoggerFactory.getLogger(GAEIMailSender.class);

    /**
     *
     * @param from from mail should be registered as google account
     * @param to to mail should be registered as google account
     * @param messageBody email message
     * @return true if message was send correct
     */
    public boolean send(String from, String to, String messageBody){
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(from));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(to));
            msg.setSubject("Home site feedback form");
            msg.setText(messageBody);
            Transport.send(msg);
            log.debug("email {} was send success", messageBody);
            log.debug("from: {} to: {}", from, to);
        } catch (AddressException e) {
            log.error(e.getMessage());
            return false;
        } catch (MessagingException e) {
            log.error(e.getMessage());
            return false;
        }
        return true;
    }
}
